#include "serialportdialog.h"
#include "ui_serialportdialog.h"
#include <QSettings>
#include <qDebug>
#include <QTimer>
#include "serialportmanager.h"
SerialPortDialog::SerialPortDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SerialPortDialog)
{
    ui->setupUi(this);
    serial = new QSerialPort;

    setWindowFlags(Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog);


    foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
	//	qDebug()<< serial.portName();
       // if(serial.open(QIODevice::ReadWrite))
        {
            ui->PortBox->addItem(serial.portName());
			ui->PortBox_2->addItem(serial.portName());
            serial.close();
        }
    }
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Com");
	ui->BaudBox->setCurrentText(app.value("BaudRate").toString());
	ui->PortBox->setCurrentText(app.value("PortName").toString());
	ui->BitBox->setCurrentText(app.value("DataBits").toString());
	ui->StopBox->setCurrentText(app.value("StopBits").toString());
	ui->ParityBox->setCurrentText(app.value("Parity").toString());

	ui->BaudBox_2->setCurrentText(app.value("BaudRateLight").toString());
	ui->PortBox_2->setCurrentText(app.value("PortNameLight").toString());
	ui->BitBox_2->setCurrentText(app.value("DataBitsLight").toString());
	ui->StopBox_2->setCurrentText(app.value("StopBitsLight").toString());
	ui->ParityBox_2->setCurrentText(app.value("ParityLight").toString());
	
    connect(ui->buttonSave, SIGNAL(clicked()), this, SLOT(SaveComConfig()));
	connect(ui->buttonCancel, &QPushButton::clicked, [=]() {
		QPushButton::close();
	});
}

SerialPortDialog::~SerialPortDialog()
{
    delete ui;
}


void SerialPortDialog::SaveComConfig()
{
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Com");
    app.setValue("BaudRate", ui->BaudBox->currentText());
    app.setValue("PortName", ui->PortBox->currentText());
    app.setValue("DataBits", ui->BitBox->currentText());
    app.setValue("StopBits", ui->StopBox->currentText());
    app.setValue("Parity", ui->ParityBox->currentText());


	app.setValue("BaudRateLight", ui->BaudBox_2->currentText());
	app.setValue("PortNameLight", ui->PortBox_2->currentText());
	app.setValue("DataBitsLight", ui->BitBox_2->currentText());
	app.setValue("StopBitsLight", ui->StopBox_2->currentText());
	app.setValue("ParityLight", ui->ParityBox_2->currentText());

	SerialPortManager::getInstance()->StopComHandler();
	SerialPortManager::getInstance()->StopComLight();

	SerialPortManager::getInstance()->OpenComHandler();
	SerialPortManager::getInstance()->OpenComLight();
}

void SerialPortDialog::closeEvent(QCloseEvent *)
{
	if (serial->isOpen())
	{
		serial->close();
	}
	serial->deleteLater(); 
}
